<template>
  <div class="login-form">
    <el-form ref="loginFormRef" autocomplete="on" :model="loginForm" label-position="left">
      <h2 class="login-title color-main">MedBox科研导航</h2>
      <el-form-item prop="email" :rules="{
        required: true,
        trigger: 'blur',
        type: 'email',
        message: '请输入正确的邮箱',
      }">
        <el-input v-model="loginForm.email" clearable name="email" type="text" autocomplete="on" placeholder="请输入邮箱"
          :prefix-icon="Message" />
      </el-form-item>
      <el-form-item prop="password" :rules="{ required: true, trigger: 'blur', message: '请输入密码' }">
        <el-input v-model="loginForm.password" clearable name="password" type="password" autocomplete="on"
          placeholder="请输入密码" show-password :prefix-icon="Key" @keyup.enter="handleLogin(loginFormRef)" />
      </el-form-item>
      <span type="danger" class="login-forget" @click="handleForget">
        忘记密码
      </span>
      <el-form-item class="login-btns">
        <el-button type="primary" :loading="loading" @click.prevent="handleLogin(loginFormRef)">
          登录
        </el-button>
      </el-form-item>
    </el-form>
    <el-dialog v-model="dialogVisible" title="找回密码" :center="true" width="350px">
      <div style="text-align: center">
        <el-input v-model="forgetEmail" clearable name="dialogVisible" type="email" autocomplete="on"
          placeholder="请输入邮箱" :prefix-icon="Message" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogConfirm">发送邮件</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { open } from '@/api/open'
import { setToken } from '@/utils/auth'
import { validEmail } from '@/utils/validate'
import { Key, Message } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
const loginFormRef = ref<FormInstance>()
const loginForm = reactive({
  email: (route.query.email as string) || '',
  password: ''
})
const loading = ref(false)
const dialogVisible = ref(false)
const forgetEmail = ref('')

const handleLogin = async (formEl: FormInstance | undefined): Promise<void> => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      loading.value = true
      route.query.type === '1' ? resetPassword() : login()
    } else {
      console.log('参数验证不合法！')
      return false
    }
  })
}
const login = async (): Promise<void> => {
  try {
    const res = await open.user.login({
      email: loginForm.email,
      password: loginForm.password
    })
    loading.value = false
    if (res.code === 0 && res.data) {
      res.data && setToken(res.data)
      window.location.href = '/'
    } else {
      ElMessage({
        message: res.message,
        type: 'error',
        duration: 1 * 1000
      })
    }
  } catch (err) {
    console.log('login', err)
    loading.value = false
  }
}
const resetPassword = async (): Promise<void> => {
  try {
    const res = await open.user.resetPassword({
      email: loginForm.email,
      password: loginForm.password,
      code: route.query.code
    })
    loading.value = false
    if (res.code === 0 && res.data) {
      setToken(res.data.Authorization)
      window.location.href = res.data.url
    }
  } catch (err) {
    console.log('resetPassword', err)
    loading.value = false
  }
}
const handleForget = (): void => {
  dialogVisible.value = true
}
const dialogConfirm = (): void => {
  if (validEmail(forgetEmail.value)) {
    forgetPass(forgetEmail.value)
  }
}
const forgetPass = async (email: string): Promise<void> => {
  try {
    const res = await open.user.forgetPass(email)
    if (res.code === 0) {
      ElMessage({
        message: res.code === 0 ? '发送成功' : '邮箱错误',
        type: res.code === 0 ? 'success' : 'error',
        duration: 1 * 1000
      })
      res.code === 0 && (dialogVisible.value = false)
    }
  } catch (err) {
    ElMessage({
      message: '邮箱错误',
      type: 'error',
      duration: 1 * 1000
    })
  }
}
</script>
<style lang="scss" scoped>
.login-form {
  position: relative;
  margin: 30px;

  .login-title {
    text-align: center;
    font-size: 25px;
    margin: 0 0 35px;
  }

  .login-forget {
    position: absolute;
    right: 0;
    bottom: 42px;
    font-size: 14px;
    color: #337ab7;
    cursor: pointer;
  }

  .login-btns {
    margin-top: 40px;
    margin-bottom: 40px;
    text-align: center;

    .el-button {
      width: 100%;
    }
  }
}
</style>
